package com.ruoyi.xqjh.lhxcgjh.controller;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.EasyExcelUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.infoRunTaskData.domain.InfoRunTaskData;
import com.ruoyi.infoRunTaskData.service.IInfoRunTaskDataService;
import com.ruoyi.xqjh.lhxcgjh.domain.Lhxcgjh;
import com.ruoyi.xqjh.lhxcgjh.domain.LhxcgjhMx;
import com.ruoyi.xqjh.lhxcgjh.service.ILhxcgjhService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 6号线采购计划Controller
 *
 * @author huacai
 * @date 2025-04-16
 */
@RestController
@RequestMapping("/xqjh/lhxcgjh")
public class LhxcgjhController extends BaseController {
    @Autowired
    private ILhxcgjhService lhxcgjhService;

    @Autowired
    private IInfoRunTaskDataService iInfoRunTaskDataService;

    /**
     * 查询6号线采购计划列表
     */
    @PreAuthorize("@ss.hasPermi('xqjh:lhxcgjh:list')")
    @GetMapping("/list")
    public TableDataInfo list(Lhxcgjh lhxcgjh) {
        startPage();
        List<Lhxcgjh> list = lhxcgjhService.selectLhxcgjhList(lhxcgjh);
        return getDataTable(list);
    }

    /**
     * 导出6号线采购计划列表
     */
    @PreAuthorize("@ss.hasPermi('xqjh:lhxcgjh:export')")
    @Log(title = "6号线采购计划" , businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Lhxcgjh lhxcgjh) {
        List<Lhxcgjh> list = lhxcgjhService.selectLhxcgjhList(lhxcgjh);
        ExcelUtil<Lhxcgjh> util = new ExcelUtil<Lhxcgjh>(Lhxcgjh.class);
        util.exportExcel(response, list, "6号线采购计划数据");
    }

    /**
     * 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Lhxcgjh> util = new ExcelUtil<Lhxcgjh>(Lhxcgjh.class);
        util.importTemplateExcel(response, "6号线采购计划数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "6号线采购计划" , businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('xqjh:lhxcgjh:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<Lhxcgjh> util = new ExcelUtil<Lhxcgjh>(Lhxcgjh.class);
        InputStream inputStream = file.getInputStream();
        List<Lhxcgjh> list = util.importExcel(inputStream);
        inputStream.close();
        int count = lhxcgjhService.batchInsertLhxcgjh(list);
        return AjaxResult.success("导入成功" + count + "条信息！");
    }

    /**
     * 获取6号线采购计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('xqjh:lhxcgjh:query')")
    @GetMapping(value = "/{lhxcgjhId}")
    public AjaxResult getInfo(@PathVariable("lhxcgjhId") String lhxcgjhId) {
        return success(lhxcgjhService.selectLhxcgjhByLhxcgjhId(lhxcgjhId));
    }

    /**
     * 新增6号线采购计划
     */
    @PreAuthorize("@ss.hasPermi('xqjh:lhxcgjh:add')")
    @Log(title = "6号线采购计划" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Lhxcgjh lhxcgjh) {
        int insertLhxcgjh = lhxcgjhService.insertLhxcgjh(lhxcgjh);

        //向流程业务表中加入数据
        InfoRunTaskData infoRunTaskData = new InfoRunTaskData();
        infoRunTaskData.setBusinessKey(lhxcgjh.getLhxcgjhId());
        infoRunTaskData.setBusinessType(16); //业务模块: 6号线采购计划
        infoRunTaskData.setBusinessTitle("6号线采购计划"); //任务名称: 6号线采购计划
        infoRunTaskData.setApplyUser(SecurityUtils.getLoginUser().getUser().getNickName());//申请人
        iInfoRunTaskDataService.insertInfoRunTaskData(infoRunTaskData);

        return toAjax(insertLhxcgjh);
    }

    /**
     * 修改6号线采购计划
     */
    @PreAuthorize("@ss.hasPermi('xqjh:lhxcgjh:edit')")
    @Log(title = "6号线采购计划" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Lhxcgjh lhxcgjh) {
//        //修改业务中间表关系数据
//        InfoRunTaskData infoRunTaskData = new InfoRunTaskData();
//        infoRunTaskData.setBusinessKey(lhxcgjh.getLhxcgjhId());
//        infoRunTaskData.setBusinessType(16); //业务模块: 6号线采购计划
//        infoRunTaskData.setBusinessTitle("6号线采购计划"); //任务名称: 6号线采购计划
//        iInfoRunTaskDataService.updateInfoRunTaskDatas(infoRunTaskData);

        return toAjax(lhxcgjhService.updateLhxcgjh(lhxcgjh));
    }

    /**
     * 删除6号线采购计划
     */
    @PreAuthorize("@ss.hasPermi('xqjh:lhxcgjh:remove')")
    @Log(title = "6号线采购计划" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{lhxcgjhIds}")
    public AjaxResult remove(@PathVariable String[] lhxcgjhIds) {
        //同时删除业务关系数据
        for (String lhxcgjhId : lhxcgjhIds) {
            Lhxcgjh lhxcgjh = lhxcgjhService.selectLhxcgjhByLhxcgjhId(lhxcgjhId);
            iInfoRunTaskDataService.deleteData(lhxcgjh.getLhxcgjhId(), 16);//业务模块: 6号线采购计划
        }
        return toAjax(lhxcgjhService.deleteLhxcgjhByLhxcgjhIds(lhxcgjhIds));
    }

    /**
     * 当6号线需求计划流程审批通过后
     * 将6号线需求计划主键ID传递过来
     * 并将6号线需求计划同步至6号线采购计划
     * lhxxqjhId: 6号线需求计划ID
     */
    @Log(title = "将6号线需求计划同步至6号线采购计划" , businessType = BusinessType.UPDATE)
    @PutMapping("/getLhxxqjhIdByOss/{lhxxqjhId}")
    public AjaxResult getLhxxqjhIdByOss(@PathVariable String lhxxqjhId) {
        return toAjax(lhxcgjhService.getLhxxqjhIdByOss(lhxxqjhId));
    }

    /**
     * 根据模板导出excel
     */
    @PostMapping("/exportWithTemplates")
    public void exportWithTemplate(HttpServletResponse response, Lhxcgjh lhxcgjh) {
        Date createTimeByDate = lhxcgjh.getCreateTime();
        String createTime = DateUtil.format(createTimeByDate, "yyyy-MM-dd");

        String lhxcgjhId = lhxcgjh.getLhxcgjhId(); //采购计划ID
        //采购计划明细
        List<LhxcgjhMx> lhxcgjhMxList = lhxcgjhService.selectLhxcgjhByLhxcgjhId(lhxcgjhId).getLhxcgjhMxList();

        for (int i = 0; i < lhxcgjhMxList.size(); i++) {
            lhxcgjhMxList.get(i).setNum(i + 1);
        }

        for (LhxcgjhMx lhxcgjhMx : lhxcgjhMxList) {
            Date sySj = lhxcgjhMx.getSySj();
            String newSySj = DateUtil.format(sySj, "yyyy-MM-dd");
            lhxcgjhMx.setNewSySj(newSySj);
        }

        double totalYsFj = lhxcgjhMxList.stream()
                .mapToDouble(LhxcgjhMx::getYsFj)
                .sum();

        // 准备导出数据
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("createTime" , createTime);
        dataMap.put("list" , lhxcgjhMxList);
        dataMap.put("totalYsFj" , totalYsFj);
        // 调用导出工具
        EasyExcelUtil.exportWithTemplate(response, dataMap, "lhxcgjh.xlsx" , "用户数据");
    }

    /**
     * 根据模板导出物资采购申请excel
     */
    @PostMapping("/exportWithLhxcgsq")
    public AjaxResult exportWithLhxcgsq(HttpServletResponse response, Lhxcgjh lhxcgjh) {
        Date createTimeByDate = lhxcgjh.getCreateTime();
        String createTime = DateUtil.format(createTimeByDate, "yyyy-MM-dd");

        String lhxcgjhId = lhxcgjh.getLhxcgjhId(); //采购计划ID
        //采购计划明细
        List<LhxcgjhMx> lhxcgjhMxList = lhxcgjhService.selectLhxcgjhByLhxcgjhId(lhxcgjhId).getLhxcgjhMxList();

        for (LhxcgjhMx lhxcgjhMx : lhxcgjhMxList) {
            if (lhxcgjhMx.getYsFj() == null) {
                return error("明细中某行预算复价为空, 请填写!");
            }
        }

        double totalYsFj = lhxcgjhMxList.stream()
                .mapToDouble(LhxcgjhMx::getYsFj)
                .sum();

        // 准备导出数据
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("createTime" , createTime);
        dataMap.put("totalYsFj" , totalYsFj);
        // 调用导出工具
        EasyExcelUtil.exportWithTemplate(response, dataMap, "6hxcgsq.xlsx" , "物资采购申请");
        return success();
    }

}
